package com.lightheart.sphr.xiaobinggan.design


import android.content.res.Resources
import android.os.Bundle
import android.support.design.widget.TabLayout
import android.support.v7.app.AppCompatActivity
import android.util.TypedValue
import android.view.View
import android.view.WindowManager
import android.widget.LinearLayout
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.gyf.barlibrary.BarHide
import com.gyf.barlibrary.ImmersionBar
import com.gyf.barlibrary.OnKeyboardListener
import com.lightheart.sphr.xiaobinggan.R
import com.lightheart.sphr.xiaobinggan.design.adapter.Adapter_Page
import com.lightheart.sphr.xiaobinggan.fragment.FragmentOne
import com.lightheart.sphr.xiaobinggan.fragment.FragmentThree
import com.lightheart.sphr.xiaobinggan.fragment.FragmentTwo
import com.scwang.smartrefresh.layout.api.RefreshHeader
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener
import com.scwang.smartrefresh.layout.util.DensityUtil
import kotlinx.android.synthetic.main.activity_materia_design.*
import java.lang.reflect.Field

class MateriaDesignActivity : AppCompatActivity() {

    private var mOffset = 0
    var isblack = false //状态栏字体是否是黑色
    var iswhite = true //状态栏字体是否是亮色
    var mImmersionBar: ImmersionBar? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_materia_design)
        initImmersionBar()
        init()
        initViewPager()
        initListener()
    }


    fun init() {
        //初始化沉浸式
        mImmersionBar?.titleBar(toolbar)?.init()
        val options = RequestOptions()
        Glide.with(this).load(R.mipmap.head)
                .apply(options.circleCrop())
                .into(iv_head)
        Glide.with(this).load(R.mipmap.head)
                .apply(options.circleCrop())
                .into(toolbar_avatar)
    }

    fun initViewPager() {
        val adapter = Adapter_Page(supportFragmentManager)
        adapter.addFragment(FragmentOne(), "主页")
        adapter.addFragment(FragmentTwo(), "日记")
        adapter.addFragment(FragmentThree(), "相册")
        view_pager.adapter = adapter
        //设置tablayout，viewpager上的标题
        tabs.setupWithViewPager(view_pager)
        tabs.setSelectedTabIndicatorColor(resources.getColor(R.color.colorPrimary))
        view_pager.currentItem = 1
        tabs.post(Runnable { setIndicator(tabs, 30, 30) })
    }

    fun initListener() {
        refreshLayout.setOnMultiPurposeListener(object : SimpleMultiPurposeListener() {
            override fun onHeaderPulling(header: RefreshHeader, percent: Float, offset: Int, bottomHeight: Int, extendHeight: Int) {
                mOffset = offset / 2
                iv_parallax.translationY = mOffset.toFloat()
            }

            override fun onHeaderReleasing(header: RefreshHeader, percent: Float, offset: Int, bottomHeight: Int, extendHeight: Int) {
                mOffset = offset / 2
                iv_parallax.translationY = mOffset.toFloat()
            }
        })

        appbar.addOnOffsetChangedListener { appBarLayout, verticalOffset ->
            iv_parallax.translationY = verticalOffset.toFloat()
            //200是appbar的高度
            if (Math.abs(verticalOffset) == DensityUtil.dp2px(200f) - toolbar.height) { //关闭
                if (iswhite) { //变黑
                    if (ImmersionBar.isSupportStatusBarDarkFont()) {
                        mImmersionBar?.statusBarDarkFont(true)?.init()
                        isblack = true
                        iswhite = false
                    }
                }
                buttonBarLayout.visibility = View.VISIBLE
                collapsing_toolbar.setContentScrimResource(R.color.white)
                iv_back.setBackgroundResource(R.mipmap.back_black)
                iv_date.setBackgroundResource(R.mipmap.date_black)
                //                    toolbar.setVisibility(View.VISIBLE);
            } else {  //展开
                if (isblack) { //变白
                    mImmersionBar?.statusBarDarkFont(false)?.init()
                    isblack = false
                    iswhite = true
                }
                buttonBarLayout.visibility = View.INVISIBLE
                collapsing_toolbar.setContentScrimResource(R.color.transparent)
                iv_back.setBackgroundResource(R.mipmap.back_white)
                iv_date.setBackgroundResource(R.mipmap.date_white)
                //                    toolbar.setVisibility(View.INVISIBLE);
            }
        }
    }

    /**
     * 通过反射修改踏遍layout的宽，其实相当于margin
     * @param tabs
     * @param leftDip
     * @param rightDip
     */
    fun setIndicator(tabs: TabLayout, leftDip: Int, rightDip: Int) {
        val tabLayout: Class<*> = tabs.javaClass
        var tabStrip: Field? = null
        try {
            tabStrip = tabLayout.getDeclaredField("mTabStrip")
        } catch (e: NoSuchFieldException) {
            e.printStackTrace()
        }
        tabStrip!!.isAccessible = true
        var llTab: LinearLayout? = null
        try {
            llTab = tabStrip[tabs] as LinearLayout
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        }
        val left = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip.toFloat(), Resources.getSystem().displayMetrics).toInt()
        val right = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip.toFloat(), Resources.getSystem().displayMetrics).toInt()
        for (i in 0 until llTab!!.childCount) {
            val child = llTab.getChildAt(i)
            child.setPadding(0, 0, 0, 0)
            val params = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1F)
            params.leftMargin = left
            params.rightMargin = right
            child.layoutParams = params
            child.invalidate()
        }
    }

    /**
     * 初始化状态栏
     */
    private fun initImmersionBar() {
        //在BaseActivity里初始化
        mImmersionBar = ImmersionBar.with(this)
        mImmersionBar
                ?.transparentStatusBar() //透明状态栏，不写默认透明色
                ?.transparentNavigationBar() //透明导航栏，不写默认黑色(设置此方法，fullScreen()方法自动为true)
                ?.transparentBar() //透明状态栏和导航栏，不写默认状态栏为透明色，导航栏为黑色（设置此方法，fullScreen()方法自动为true）
                ?.statusBarAlpha(0.3f) //状态栏透明度，不写默认0.0f
                ?.navigationBarAlpha(0.4f) //导航栏透明度，不写默认0.0F
                ?.barAlpha(0.3f) //状态栏和导航栏透明度，不写默认0.0f
                ?.statusBarDarkFont(true) //状态栏字体是深色，不写默认为亮色
                ?.flymeOSStatusBarFontColor(R.color.black) //修改flyme OS状态栏字体颜色
                ?.fullScreen(true) //有导航栏的情况下，activity全屏显示，也就是activity最下面被导航栏覆盖，不写默认非全屏
                ?.hideBar(BarHide.FLAG_HIDE_BAR) //隐藏状态栏或导航栏或两者，不写默认不隐藏
                ?.fitsSystemWindows(true) //解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色
                ?.supportActionBar(true) //支持ActionBar使用
                ?.removeSupportAllView() //移除全部view支持
                ?.addTag("tag") //给以上设置的参数打标记
                ?.getTag("tag") //根据tag获得沉浸式参数
                ?.reset() //重置所以沉浸式参数
                ?.keyboardEnable(false) //解决软键盘与底部输入框冲突问题，默认为false
                ?.setOnKeyboardListener(OnKeyboardListener { isPopup, keyboardHeight ->
                    //软键盘监听回调
                    //                        LogUtils.e(isPopup);  //isPopup为true，软键盘弹出，为false，软键盘关闭
                })
                ?.keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) //单独指定软键盘模式
                ?.init() //必须调用方可沉浸式
    }

    override fun onDestroy() {
        super.onDestroy()
        mImmersionBar?.let {
            it.destroy()
        }
    }

}